package com.fengye.algorithms.leecode;

import java.util.Arrays;

/**
 * @Author fengye
 * @Date 2023/4/10 9:22
 **/
public class CheckInclusion567 {
    public boolean checkInclusion2(String s1, String s2) {
        if(s1.length() > s2.length()) {
            return false;
        }
        if(s1.length() == 1) {
            return s2.contains(s1);
        }

        char[] s1Arr = s1.toCharArray();
        Arrays.sort(s1Arr);
        for(int i=0;i<s2.length()-s1.length()+1;i++) {
            String sub  = s2.substring(i, i+s1.length());
            char[] subArr = sub.toCharArray();
            Arrays.sort(subArr);
            if(new String(subArr).equals(new String(s1Arr))) {
                return true;
            }
        }

        return false;
    }

    public boolean checkInclusion(String s1, String s2) {
        int n = s1.length();
        int m = s2.length();
        if(n > m) {
            return false;
        }
        if(n == 1) {
            return s2.contains(s1);
        }

        int[] cnt1 = new int[26];
        int[] cnt2 = new int[26];
        for(int i=0;i<n;i++) {
            ++cnt1[s1.charAt(i) - 'a'];
            ++cnt2[s2.charAt(i) - 'a'];
        }

        if(Arrays.equals(cnt1,cnt2)) {
            return true;
        }

        for(int i=n;i<m;i++) {
            ++cnt2[s2.charAt(i) - 'a'];
            --cnt2[s2.charAt(i-n) - 'a'];
            if(Arrays.equals(cnt1,cnt2)) {
                return true;
            }
        }
        return false;
    }
}
